package com.wn.common.ktx

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * @Author: wn
 * @Date: 2022/12/9 10:48
 * @Description: Fragment 的 扩展 函数  属性
 */

/*
 * Fragment中使用DataBinding时 onCreateView 的简化
 * layout 布局文件
 * return 返回一个 dataBinding 的对象实例
 * */
fun <T : ViewDataBinding> Fragment.viewDataBind(
  @LayoutRes layout: Int,
  container: ViewGroup?,
): T =
  DataBindingUtil.inflate(layoutInflater, layout, container, false)

/*
 * Fragment中使用DataBinding  子类继承时 指定 <dataBinding>
 * 无需布局文件布局文件
 * return 返回一个 dataBinding 的对象实例
 * */
@Suppress("UNCHECKED_CAST")
fun <T : ViewBinding> Fragment.viewDataBind(
  inflater: LayoutInflater,
  container: ViewGroup?
): T {
  val vbClass =
    (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments.filterIsInstance<Class<T>>()
  val inflate = vbClass[0].getDeclaredMethod(
    "inflate",
    LayoutInflater::class.java,
    ViewGroup::class.java,
    Boolean::class.java
  )
  return inflate.invoke(null, inflater, container, false) as T
}